package com.example.flutter_demo2.plugins.router

import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.google.gson.Gson
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.BasicMessageChannel
import io.flutter.plugin.common.StringCodec
import java.util.*

object FlutterRouterObserver {
    // BasicMessageChannel的key
    private const val FLUTTER_MIX_STACK_CHANNEL = "mix_stack_message_channel"

    private lateinit var mMessageChannel: BasicMessageChannel<String>
    private var mCallback: ((status: Int) -> Unit)? = null

    // 注意这里不是flutter的栈信息，而是宿主观察者集合
    // 所有宿主activity都是观察者，观察flutter栈动态，这些观察者组成一个集合，宿主死亡集合pop
    private val mHostObservers: Stack<RouteCallback> by lazy {
        Stack()
    }

    fun initChannel(engine: FlutterEngine, block: (status: Int) -> Unit) {
        mMessageChannel = BasicMessageChannel(
            engine.dartExecutor,
            FLUTTER_MIX_STACK_CHANNEL,
            StringCodec.INSTANCE
        )
        mMessageChannel.setMessageHandler(mMessageHandler)
        this.mCallback = block
        block(1)
    }

    // basicMessageChannel消息处理器
    private val mMessageHandler =
        BasicMessageChannel.MessageHandler<String> { message, _ ->
//            if (FLUTTER_ENGINE_INIT_FINISH == message) {
//                initCallback?.run {
//                    this(2)
//                }
//            }
            //处理其他交互信息
//            else {
            try {
                val received = Gson().fromJson(message, ReceivedMessage::class.java)
                parseMessage(received)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
//        }

    // 添加route的host监听
    fun addHostCallback(callback: RouteCallback) {
        mHostObservers.push(callback)
        // onDestroy时移除监听，注解已过时
//        callback.getLifecycleOwner().lifecycle.addObserver(object : LifecycleObserver {
//            @OnLifecycleEvent(androidx.lifecycle.Lifecycle.Event.ON_DESTROY)
//            fun onDestroy() {
//                mHostObservers.pop()
//            }
//        })
        callback.getLifecycleOwner().lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onDestroy(owner: LifecycleOwner) {
                super.onDestroy(owner)
                mHostObservers.pop()
            }
        })
    }

    private fun parseMessage(message: ReceivedMessage) {
        if (mHostObservers.isEmpty()) {
            return
        }
        val peek = mHostObservers.peek()
        when (message.operateType) {
            //打开native
            0 -> {
                val nativeRoute = message.nativeRoute!!
                peek.routeNative(nativeRoute, message.nativeParams)
            }
            //Flutter栈更新
            1 -> {
                when (message.flutterType) {
                    //入栈
                    0 -> {
                        peek.onPush(message.flutterCurrentRoute!!)
                    }
                    //出栈
                    1 -> {
                        peek.onPop(message.flutterCurrentRoute!!)
                    }
                    //替换
                    2 -> {
                        peek.onReplace(message.flutterCurrentRoute!!, message.flutterPreRoute!!)
                    }
                    //移除
                    3 -> {

                    }
                }
            }
        }
    }
}


/**
 * flutter路由变化回调
 */
interface RouteCallback {

    fun onPush(route: String)

    fun onPop(route: String)

    fun onReplace(newRoute: String, oldRoute: String)

    fun onRemove(route: String)

    fun routeNative(nativeRoute: String, params: HashMap<String, Any>? = null)

    fun getLifecycleOwner(): LifecycleOwner
}